package com.shiwaixiangcun.customer.module.heath

import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import android.widget.ImageView
import android.widget.RelativeLayout
import com.google.gson.reflect.TypeToken
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.shiwaixiangcun.customer.ConfigSps
import com.shiwaixiangcun.customer.GlobalApi
import com.shiwaixiangcun.customer.R
import com.shiwaixiangcun.customer.base.BaseActivity
import com.shiwaixiangcun.customer.event.EventUtil
import com.shiwaixiangcun.customer.event.SimpleEvent
import com.shiwaixiangcun.customer.network.ResponseConfig
import com.shiwaixiangcun.customer.ui.activity.AddFamilyActivity
import com.shiwaixiangcun.customer.utils.AppSharePreferenceMgr
import com.shiwaixiangcun.customer.utils.JsonUtil
import com.shiwaixiangcun.customer.utils.RefreshTokenUtil
import kotlinx.android.synthetic.main.activity_health_main.*
import kotlinx.android.synthetic.main.top_bar_white.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**
 * 健康管理首页
 */
class HealthMainActivity : BaseActivity(), View.OnClickListener {


    companion object {
        val REQUEST_DATA: Int = 0x1001
        val A2F: Int = 0x1010
        val REQUEST_LISTENER: Int = 0x1011
    }

    var refreshToken: String? = null
    var strToken: String? = null
    var mAdapter: AdapterFamilyHealth? = null
    var userID: Long? = 0L
    var mList: MutableList<HealthFamilyData>? = null
    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.back_left -> {
                finish()
            }
            R.id.tv_add_family -> {
                readyGo(AddFamilyActivity::class.java)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_health_main)
        EventUtil.getInstance().register(this)
        initViewAndEvent()
        initData()
    }

    /**
     * 获取自己和家人的数据
     */
    private fun initData() {

        strToken = AppSharePreferenceMgr.get(mContext, ConfigSps.CURRENT_TOKEN, "") as String
        OkGo.get<String>(GlobalApi.familyHealthList)
                .params("access_token", strToken)
                .execute(object : StringCallback() {

                    override fun onSuccess(response: Response<String>?) {
                        val type = object : TypeToken<CommonListEntity<HealthFamilyData>>() {}.type
                        val commonListEntity = JsonUtil.fromJson<CommonListEntity<HealthFamilyData>>(response?.body(), type)

                        when (commonListEntity.responseCode) {
                            ResponseConfig.SUCCESS -> {
                                var showData = false
                                commonListEntity.data.forEach {
                                    if (it.totalStatus != null) {
                                        showData = true
                                    }
                                }
                                if (showData) {
                                    clayout_empty.visibility = View.GONE
                                    layout_data.visibility = View.VISIBLE
                                    EventUtil.getInstance().post(SimpleEvent(SimpleEvent.HEALTH_FAMILY_LIST, REQUEST_DATA, commonListEntity.data))
                                } else {
                                    clayout_empty.visibility = View.VISIBLE
                                    layout_data.visibility = View.INVISIBLE
                                }
                            }
                            ResponseConfig.TOKEN_INVALID -> {
                                showToastShort("当前登录失效")
                                clayout_empty.visibility = View.VISIBLE
                                layout_data.visibility = View.INVISIBLE
                                RefreshTokenUtil.refreshToken(mContext, refreshToken)
                            }
                        }

                    }
                })


    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun updateUI(simpleEvent: SimpleEvent) {
        if (simpleEvent.mEventType != SimpleEvent.HEALTH_FAMILY_LIST) {
            return
        }
        when (simpleEvent.mEventValue) {
            REQUEST_DATA -> {

                mList?.clear()

                val data = simpleEvent.data as List<HealthFamilyData>

                userID = data[0].customerId

                EventUtil.getInstance().postSticky(SimpleEvent(SimpleEvent.HEALTH_CHANGE_FAMILY, A2F, userID))

                if (data.size == 1) {
                    Rlayout_family.removeAllViews()
                    val ivAdd = ImageView(this)
                    ivAdd.setImageResource(R.drawable.bg_health_add_family)
                    ivAdd.scaleType = ImageView.ScaleType.FIT_XY


                    val layoutParams = Rlayout_family.layoutParams

                    layoutParams.width = RelativeLayout.LayoutParams.MATCH_PARENT
                    Rlayout_family.addView(ivAdd, layoutParams)
//                    divider.visibility = View.GONE
                    ivAdd.setOnClickListener { readyGo(AddFamilyActivity::class.java) }

                } else {
                    mList?.addAll(data)
                    mList?.let {
                        mAdapter?.addData(it)
                        mAdapter?.notifyDataSetChanged()
                    }
                }
            }

            REQUEST_LISTENER -> {
                initData()
            }
        }

    }

    private fun initViewAndEvent() {

        tv_page_name.text = "健康管理"
        back_left.setOnClickListener(this)
        refreshToken = AppSharePreferenceMgr.get(mContext, ConfigSps.CURRENT_REFRESH_TOKEN, "") as String

        mList = ArrayList()
        mAdapter = AdapterFamilyHealth()

        //设置RecyclerView
        val layoutManager = LinearLayoutManager(this)
        layoutManager.orientation = LinearLayoutManager.HORIZONTAL
        rv_family.layoutManager = layoutManager
        rv_family.adapter = mAdapter
        //设置Fragment
        val beginTransaction = supportFragmentManager.beginTransaction()
        val healthFragment = HealthFragment.newInstance(userID)
        beginTransaction?.add(R.id.flayout_health, healthFragment)
        beginTransaction.commit()

        tv_add_family.setOnClickListener(this)

        mAdapter?.setOnItemClickListener { adapter, view, position ->
            mAdapter?.setSelected(position)
            val healthFamilyData = adapter.data[position] as HealthFamilyData
            EventUtil.getInstance().postSticky(SimpleEvent(SimpleEvent.HEALTH_CHANGE_FAMILY, A2F, healthFamilyData.customerId))
        }
    }

    override fun onDestroy() {
        EventUtil.getInstance().unregister(this)
        super.onDestroy()
    }

}
